package com.wanmait.teatrain.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wanmait.teatrain.service.CourseService;
import com.wanmait.teatrain.utils.AjaxResult;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.wanmait.teatrain.entity.Course;
import com.wanmait.teatrain.entity.CourseResource;
import com.wanmait.teatrain.service.CourseResourceService;
import com.wanmait.teatrain.service.CourseService;
import com.wanmait.teatrain.utils.AjaxResult;

import javax.annotation.Resource;
import java.util.AbstractMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程表 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2025-10-22
 */
@RestController
@RequestMapping("/course")
public class CourseController {
    @Resource
    private CourseService courseService;

    @Resource
    private CourseResourceService courseResourceService;

    @RequestMapping("save")
    public AjaxResult saveCourse(@RequestBody Course course) {
        courseService.save(course);
        List<Integer> ids = course.getResourceIds();
        Integer courseId = course.getId();
        if (ids != null && !ids.isEmpty()) {
            for (Integer resourceId : ids) {
                CourseResource courseResource = new CourseResource();
                courseResource.setCourseId(courseId);
                courseResource.setResourceId(resourceId);
                courseResource.setCreateTime(new Date());
                courseResource.setEnable(true);
                courseResource.setSort(ids.indexOf(resourceId) + 1);
                courseResourceService.save(courseResource);
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("selectAllCourse")
    public AjaxResult selectAllCourse(@RequestParam("pageNum") Integer pageNum,
                                      @RequestParam(value = "search", required = false) String search,
                                      @RequestParam(value = "isStop",required = false) Boolean isStop){
        return courseService.selectAllCourse(pageNum,search,isStop);
    }

    // 添加分页查询接口
    @GetMapping("list")
    public AjaxResult getCourseList() {
        List<Course> courseList = courseService.list();
        return AjaxResult.success().put("list", courseList);
    }

    @GetMapping("delete")
    public AjaxResult deleteCourse(@RequestParam("id") Integer id) {
        courseService.removeById(id);
        return AjaxResult.success();
    }

    @PostMapping("update")
    public AjaxResult updateCourse(@RequestBody Course course) {
        courseService.updateById(course);
        Integer courseId = course.getId();
        List<Integer> newResourceIds = course.getResourceIds();
        newResourceIds = newResourceIds == null ? Collections.emptyList() : newResourceIds;
        LambdaQueryWrapper<CourseResource> existingWrapper = new LambdaQueryWrapper<>();
        existingWrapper.eq(CourseResource::getCourseId, courseId);
        List<CourseResource> existingResources = courseResourceService.list(existingWrapper);
        Map<Integer, CourseResource> existingResourceMap = existingResources.stream()
                .collect(Collectors.toMap(CourseResource::getResourceId, resource -> resource));
        for (Integer resourceId : newResourceIds) {
            // 获取排序（索引+1）
            int sort = newResourceIds.indexOf(resourceId) + 1;
            CourseResource existing = existingResourceMap.get(resourceId);
            if (existing == null) {
                CourseResource newResource = new CourseResource();
                newResource.setCourseId(courseId);
                newResource.setResourceId(resourceId);
                newResource.setCreateTime(new Date());
                newResource.setEnable(true);
                newResource.setSort(sort);
                courseResourceService.save(newResource);
            } else {
                if (!existing.getEnable()) {
                    existing.setEnable(true);
                }
                existing.setSort(sort);
                courseResourceService.updateById(existing);
            }
        }
        Set<Integer> existingResourceIdSet = existingResourceMap.keySet();
        List<Integer> finalNewResourceIds = newResourceIds;
        Set<Integer> toDeleteIds = existingResourceIdSet.stream()
                .filter(id -> !finalNewResourceIds.contains(id))
                .collect(Collectors.toSet());
        if (!toDeleteIds.isEmpty()) {
            LambdaUpdateWrapper<CourseResource> deleteWrapper = new LambdaUpdateWrapper<>();
            deleteWrapper.eq(CourseResource::getCourseId, courseId)
                    .in(CourseResource::getResourceId, toDeleteIds)
                    .set(CourseResource::getEnable, false);
            courseResourceService.update(deleteWrapper);
        }
        return AjaxResult.success();
    }
}